<template>
    <div>
        <el-page-header content="编辑新闻" @back="handleBack"  title="新闻管理"></el-page-header>
        <el-form
            :model="newsForm"
            :rules="newsFormRules"
            ref="newsFormRef"
            label-width="80px"
            >
                <el-form-item label="标题" prop="title">
                    <el-input v-model="newsForm.title"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <editor @event="handleChange" :content="newsForm.content" v-if="newsForm.content"/>
                </el-form-item>
                <el-form-item label="类别" prop="category">
                    <el-select v-model="newsForm.category" placeholder="请选择分类" style="width:100%">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="封面">
                    <div class="box-card">
                        <img class="the_img" :src="newsForm.cover" alt="">
                        <div class="btn-box">
                            <input type="file" accept="image/*" style="display: none" id="iptRef" @change="onFileChange" />
                            <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button> 
                        </div>
                    </div>
                </el-form-item> 
                <el-button style="margin-left:48%" type="primary" @click="submitForm()">更新新闻</el-button>
        </el-form>
    </div>
</template>

<script setup>
import {ref,reactive,onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {editNewAPI, getNewCurrentAPI} from '@/api'
import {useRouter,useRoute} from 'vue-router'
import editor from "@/components/editor/Editor"
const router=useRouter()
const route=useRoute()

const newsFormRef=ref()
const newsForm=reactive({
    title:"",
    content:"",
    category:1, //1最新动态 2典型案例 3通知公告
    cover:"",
    // isPublish //2未发布  1已发布
})
const newsFormRules=reactive({
    title:[{required:true,message:"请输入标题",trigger:"blur"}],
    content:[{required:true,message:"请输入内容",trigger:"blur"}],
    category:[{required:true,message:"请选择分类",trigger:"blur"}]
})

// 每次editor内容改变的回调
const handleChange=(data)=>{
    newsForm.content=data
    console.log(data);
}

// 新闻类别
const options=[
    {label:'最新动态',value:1},
    {label:'典型类别',value:2},
    {label:'通知公告',value:3}
]

// 编辑新闻
const submitForm=()=>{
    newsFormRef.value.validate(async (valid)=>{
        if(valid){
            console.log('23/',newsForm);
            const {data:res}=await editNewAPI(newsForm)
            // console.log('res',res);
            
            if(res.status!==0) {
                ElMessage.error('编辑失败')
            } else{
                ElMessage.success('编辑成功')
                router.back()
            }

        }
    })
}
const handleBack=()=>{
    router.back()
}

//获取当前页面数据
onMounted(async()=>{
    const {data:res}=await getNewCurrentAPI(route.params.id)
    // 合并对象
    Object.assign(newsForm,res.data.results[0])
}) 

// 图片
const chooseImg=function () {
    // 模拟点击行为
    document.getElementById('iptRef').click()
  }
const onFileChange=function (e) {
    const files = e.target.files // 拿到用户选择的文件数组
    console.log(files);
    if (files.length === 0) {
     
    } else {
      // 解决方案2：文件->base64字符串（此字符串是可以发给后台的）
      const fr = new FileReader()
      fr.readAsDataURL(files[0]) // 传入文件对象开始读
      fr.onload = (e) => { 
        newsForm.cover = e.target.result // 赋予给变量，让他显示在img的src里
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form{
    margin-top:50px
}
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
.the_img{
    width: 150px;
    height: 150px;
}
</style>